const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router();
// 购物车列表
router.post('/zd/getCart', async ctx => {
    let usr = ctx.user
    let tenantId = usr.tenantId
    let sql = `select a.*,b.name,b.spec,b.unit1,b.unit2,
       isnull(c.price,0) price,
       isnull(e.price,0) hisUnit1Price,
       isnull(e.price,0) hisUnit2Price,
       isnull(b.price2,0) unit1Price , 
       isnull(c.deduction,0) deduction , 
       isnull(b.imgUrl,'') imgUrl , 
       case when a.unit=b.unit1 then b.spec else 1 end calNum ,
       f.sendQty,f.buyQty 
        from cart_zd a  
        inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id and a.tenantId=${tenantId} and a.buId=${usr.buId} 
        left join (select * from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId} and transType=150601) c on a.tenantId=c.tenantId and a.id=c.invId and a.unit=c.unit
        left join (select * from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId} and calNum<>1 and transType=150601) d on a.tenantId=d.tenantId and a.id=d.invId 
        left join (select * from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId} and calNum=1 and transType=150601) e on a.tenantId=e.tenantId and a.id=e.invId 
        left join (select * from v_send_last where tenantId=${tenantId} and buId=${usr.buId} ) f on a.tenantId=f.tenantId and b.id=f.invId 
    `
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    list.map(row => {
        let price = tool.xe.toNumber(row.price)
        // 没有价格
        if(!price) {
            if(row.calNum === 1) {
                // 如果是零售单位
                let pr  = tool.xe.toNumber(row.histUnit2Price)
                if(!pr) {
                    row.price = tool.xe.round(tool.xe.divide(row.unit1Price,row.spec),2)
                }
            }
            else {
                // 如果是大单位
                row.price = tool.xe.toNumber(row.histUnit1Price)
                if(!row.price) {
                    row.price = tool.xe.toNumber(row.unit1Price)
                }
            }
        }
    })
    list.map(row => {
        row.amount = tool.xe.multiply(row.qty, tool.xe.subtract(row.price,row.deduction))
        row.price = tool.xe.toFixed(row.price, 2)
        row.deduction = tool.xe.toNumber(row.deduction)
        if(row.buyQty) {
            row.send = `买${row.buyQty}赠${row.sendQty}`
        }
    })

    return ctx.suc('', {list: list})
})

module.exports = router;
